package com.example.canalclientsync.canal.handler;

import com.example.canalclientsync.canal.mapper.db1.ModelMapper;
import com.example.canalclientsync.canal.service.ModelService;
import com.example.canalclientsync.canal.mapper.db1.DirMapper;
import com.example.canalclientsync.canal.po.Dir;
import com.example.canalclientsync.canal.po.FolderModelRelation;
import com.example.canalclientsync.canal.po.VirtualModel;
import com.example.canalclientsync.es.document.EsModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.util.CollectionUtils;
//import top.javatool.canal.client.annotation.CanalTable;
//import top.javatool.canal.client.handler.EntryHandler;

import javax.annotation.Resource;
import java.util.List;

/**
 * 文件移动
 *
 * @author chen.cr
 * @since 2023/9/20
 */
//@Component
//@CanalTable("f_folder_virtual_model_relationship")
@Slf4j
public class FolderModelRelationHandler implements EntryHandler<FolderModelRelation> {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Resource
    private ModelMapper modelMapper;
    @Resource
    private ModelService modelService;
    @Resource
    private DirMapper dirMapper;


    @Override
    public void insert(FolderModelRelation folderModelRelation) {
        log.info("insert folderModelRelation");
        log.info("nothing to do");
    }

    @Override
    public void update(FolderModelRelation before, FolderModelRelation after) {
        log.info("update folderModelRelation");
        List<VirtualModel> models = modelMapper.findByMasterIdAndTenantId(after.getMasterId(), after.getTenantId());
        if (!CollectionUtils.isEmpty(models)) {
            Dir parentDir = dirMapper.findByDirIdAndTenantId(after.getFolderId(), after.getTenantId());
            for (VirtualModel model : models) {
                EsModel esModel = modelService.buildFromVirtualModel(model, parentDir);
                if (esModel != null) {
                    elasticsearchRestTemplate.save(esModel);
                }
            }
        }
        log.info("ES 更新folderModelRelation相关模型数据成功");
    }

    @Override
    public void delete(FolderModelRelation folderModelRelation) {
        log.info("delete folderModelRelation");
        log.info("nothing to do");
    }
}
